package aerouacmsla.interfazDeUsuario;

import aerouacmsla.procedimientos.BDConexion;
import aerouacmsla.procedimientos.CreateTables;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.Timer;

/**
 *
 * @author Marco
 */
public class VentanaMonitor extends javax.swing.JFrame {
    
    private BDConexion miConexion;
    private String idCiudad;
    private CreateTables modeloTabla = new CreateTables();
    private JFrame padre;
    private String fechaActual;
    private Timer timerSalidas = new Timer (5000, new ActionListener () {
            public void actionPerformed(ActionEvent e) {
                try {
                    /* checa las horas checar los vuelos
                     * actuales marcar los vuelos en curso cuando
                     * sea la hora correcta*/
                    setTablaVuelosSalidas();
                    Calendar fechaSalida = new GregorianCalendar();
                    int annio = fechaSalida.get(Calendar.YEAR);
                    int mes = fechaSalida.get(Calendar.MONTH) + 1;
                    int dia = fechaSalida.get(Calendar.DAY_OF_MONTH);

                    String horaActual = fechaSalida.get(Calendar.HOUR_OF_DAY) + "";
                    String minutoActual = fechaSalida.get(Calendar.MINUTE) + "";

                    if (horaActual.length() < 2)
                        horaActual = "0" + horaActual;
                    if (minutoActual.length() < 2)
                        minutoActual = "0" + minutoActual;

                    String horaCompleta = horaActual + ":" + minutoActual;

                    String SQL = "SELECT * FROM vuelo WHERE origen "
                        + "='" + getIdCiudad() + "' && estado='Incompleto' && fecha='" + annio + "-"
                        + mes + "-" + dia + "';";
                    getMiConexion().sendSQLQuery(SQL);
                    while (getMiConexion().getResultado().next()){
                        String hora = getMiConexion().getResultado().getString("hora_salida");
                        String horaMinuto[] = hora.split(":");
                        String horaAComparar = horaMinuto[0] + ":" + horaMinuto[1];
                        if (horaCompleta.equals(horaAComparar)){
                            String idVuelo = getMiConexion().getResultado().getString("id_vuelo");
                            getMiConexion().sendSQL("UPDATE vuelo SET estado = 'En Curso' WHERE id_vuelo ='" + idVuelo + "';");
                            setTablaVuelosSalidas();
                        }
                    }
                } catch (Exception error) {
                    System.out.println("Error timer");
                }
            }
         });

    public VentanaMonitor() {
        initComponents();
    }
    public VentanaMonitor(BDConexion miConexion, String idCiudad, JFrame padre) {
        initComponents();
        setMiConexion(miConexion);
        setIdCiudad(idCiudad);
        setPadre(padre);
        //Se llena la tabla con los vuelos incompletos
        setTablaVuelosLlegadas();
        setTablaVuelosSalidas();
        //El monitor siempre debe tener la hora y fecha correctas
        int n = JOptionPane.showConfirmDialog(
        this,
        getFechaActual() + "  La hora y fecha son correctos?",
        "Pregunta Importante",
        JOptionPane.YES_NO_OPTION);
        if (n == 1) {
            JOptionPane.showMessageDialog(this,
            "Para el buen funcionamiento la hora y fecha deben estar correctamente configurados" +
                    ", corrijalo y vuelva a iniciar el programa.",
            "Corrija los datos",
            JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }
        timerSalidas.start();
        //Cada 2 minutos la tabla se actualiza automaticamente
        Timer timer = new Timer (120000, new ActionListener () {
            public void actionPerformed(ActionEvent e) {
                try {
                    setTablaVuelosLlegadas();
                } catch (Exception error) {
                    System.out.println("Error timer");
                }
            }
         });
         timer.start();
    }

    public void setTablaVuelosLlegadas(){
        Calendar fecha = new GregorianCalendar();
        int annio = fecha.get(Calendar.YEAR);
        int mes = fecha.get(Calendar.MONTH) + 1;
        int dia = fecha.get(Calendar.DAY_OF_MONTH);
        String fechaActualGenerada = dia + "/" + mes + "/" + annio + " "
                + fecha.get(Calendar.HOUR_OF_DAY) + ":" + fecha.get(Calendar.MINUTE);
        setFechaActual(fechaActualGenerada);
        String SQL = "SELECT * FROM vuelo WHERE destino "
               + "='" + getIdCiudad() + "' && estado='En curso' && fecha='" + annio + "-"
               + mes + "-" + dia + "';";
        jTable1.setModel(getModeloTabla().getTableModel(getMiConexion().sendSQLQuery(SQL)));
    }
    public void setTablaVuelosSalidas(){
        Calendar fecha = new GregorianCalendar();
        int annio = fecha.get(Calendar.YEAR);
        int mes = fecha.get(Calendar.MONTH) + 1;
        int dia = fecha.get(Calendar.DAY_OF_MONTH);
        String SQL = "SELECT * FROM vuelo WHERE origen "
               + "='" + getIdCiudad() + "' && estado='Incompleto' && fecha='" + annio + "-"
               + mes + "-" + dia + "';";
        jTable2.setModel(getModeloTabla().getTableModel(getMiConexion().sendSQLQuery(SQL)));
    }

    public BDConexion getMiConexion() {
        return miConexion;
    }

    public void setMiConexion(BDConexion miConexion) {
        this.miConexion = miConexion;
    }

    public String getIdCiudad() {
        return idCiudad;
    }

    public void setIdCiudad(String idCiudad) {
        this.idCiudad = idCiudad;
    }

    public CreateTables getModeloTabla() {
        return modeloTabla;
    }

    public void setModeloTabla(CreateTables modeloTabla) {
        this.modeloTabla = modeloTabla;
    }

    public JFrame getPadre() {
        return padre;
    }

    public void setPadre(JFrame padre) {
        this.padre = padre;
    }

    public String getFechaActual() {
        return fechaActual;
    }

    public void setFechaActual(String fechaActual) {
        this.fechaActual = fechaActual;
    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jCheckBox1 = new javax.swing.JCheckBox();
        campoIdVueloSalida = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        campoIdVueloLlegada = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Monitor");
        setIconImage(new ImageIcon(getClass().getResource("/Recursos/IconoMonitor32px.png")).getImage());
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.getTableHeader().setReorderingAllowed(false);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jLabel2.setText("Llegadas:");

        jLabel3.setText("Salidas:");

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable2.getTableHeader().setReorderingAllowed(false);
        jTable2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable2MouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(jTable2);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Controles Salidas"));

        jCheckBox1.setSelected(true);
        jCheckBox1.setText("Modo Automatico");
        jCheckBox1.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jCheckBox1StateChanged(evt);
            }
        });

        campoIdVueloSalida.setEditable(false);
        campoIdVueloSalida.setToolTipText("Seleccione el id desde la tabla");

        jButton2.setText("Marcar Como En Curso");
        jButton2.setEnabled(false);
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton2MouseClicked(evt);
            }
        });

        jButton4.setText("Actualizar Datos");
        jButton4.setEnabled(false);
        jButton4.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton4MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jButton4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jCheckBox1, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(campoIdVueloSalida, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 189, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jCheckBox1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(campoIdVueloSalida, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton4)
                .addContainerGap(152, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Controles Llegadas"));

        jButton1.setText("Marcar Como Completado");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        campoIdVueloLlegada.setEditable(false);
        campoIdVueloLlegada.setToolTipText("Seleccione el id desde la tabla");

        jLabel1.setText("ID Vuelo");

        jButton3.setText("Actualizar Datos");
        jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton3MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jButton3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(campoIdVueloLlegada, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 189, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(campoIdVueloLlegada, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3)
                .addContainerGap(100, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addContainerGap())
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel2)
                            .addContainerGap())
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 506, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 506, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 225, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 289, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        //Poniendo el id en el texfield
        int fila = jTable1.getSelectedRow();
        //Se toma el id del vuelo segun sea seleccionado en la tabla
        String idVueloSeleccionado = jTable1.getValueAt(fila, 0).toString();
        campoIdVueloLlegada.setText(idVueloSeleccionado);
    }//GEN-LAST:event_jTable1MouseClicked

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        getPadre().setVisible(true);
    }//GEN-LAST:event_formWindowClosing

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
        //Cambiando estados tanto del avion como del vuelo a completos y en tierra
        if (!campoIdVueloLlegada.getText().isEmpty()){
            getMiConexion().sendSQL("UPDATE vuelo SET estado='Completado' WHERE id_vuelo ='" + campoIdVueloLlegada.getText() + "';");
            getMiConexion().sendSQLQuery("SELECT id_avion FROM vuelo WHERE id_vuelo ='" + campoIdVueloLlegada.getText() + "';");
            try {
                if (getMiConexion().getResultado().next()) {
                    getMiConexion().sendSQL("UPDATE avion SET id_estado= 3, "
                            + "ubicacion='" + getIdCiudad() + "' WHERE id_avion =" + getMiConexion().getResultado().getInt("id_avion") + ";");
                }
                setTablaVuelosLlegadas();
            } catch (SQLException ex) {
                Logger.getLogger(VentanaMonitor.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        campoIdVueloLlegada.setText(null);
    }//GEN-LAST:event_jButton1MouseClicked

    private void jTable2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable2MouseClicked
        //Poniendo el id en el texfield
        int fila = jTable2.getSelectedRow();
        //Se toma el id del vuelo segun sea seleccionado en la tabla
        String idVueloSeleccionado = jTable2.getValueAt(fila, 0).toString();
        campoIdVueloSalida.setText(idVueloSeleccionado);
    }//GEN-LAST:event_jTable2MouseClicked

    private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked
        //Cambiando estados tanto del avion como del vuelo a completos y en tierra
        if (!campoIdVueloSalida.getText().isEmpty()){
            getMiConexion().sendSQL("UPDATE vuelo SET estado='En curso' WHERE id_vuelo ='" + campoIdVueloSalida.getText() + "';");
            getMiConexion().sendSQLQuery("SELECT id_avion FROM vuelo WHERE id_vuelo ='" + campoIdVueloSalida.getText() + "';");
            try {
                if (getMiConexion().getResultado().next()) {
                    getMiConexion().sendSQL("UPDATE avion SET id_estado= 1, "
                            + "ubicacion='" + getIdCiudad() + "' WHERE id_avion =" + getMiConexion().getResultado().getInt("id_avion") + ";");
                }
                setTablaVuelosSalidas();
                campoIdVueloSalida.setText(null);
            } catch (SQLException ex) {
                Logger.getLogger(VentanaMonitor.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        campoIdVueloLlegada.setText(null);
    }//GEN-LAST:event_jButton2MouseClicked

    private void jCheckBox1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jCheckBox1StateChanged
        if (!jCheckBox1.isSelected()){
            jButton2.setEnabled(true);
            jButton4.setEnabled(true);
            timerSalidas.stop();
        }
        else {
            jButton2.setEnabled(false);
            jButton4.setEnabled(false);
            timerSalidas.start();
        }
    }//GEN-LAST:event_jCheckBox1StateChanged

    private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseClicked
        setTablaVuelosLlegadas();
    }//GEN-LAST:event_jButton3MouseClicked

    private void jButton4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton4MouseClicked
        setTablaVuelosSalidas();
    }//GEN-LAST:event_jButton4MouseClicked

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VentanaMonitor().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField campoIdVueloLlegada;
    private javax.swing.JTextField campoIdVueloSalida;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    // End of variables declaration//GEN-END:variables

}
